import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { getBackMobileVerCode,deleteUserInfo,middleStageLogin } from '../services/api';
import { setAuthority } from '../utils/authority';
import { reloadAuthorized } from '../utils/Authorized';
import errMassage from '../utils/errMassage';
// import { getPageQuery } from '../utils/utils';

export default {
  namespace: 'login',

  state: {
    status: undefined,
    massage : undefined,
  },

  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(middleStageLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: {response,type:payload.type,currentAuthority:"admin"},
      });
      // Login successfully
      if (response.success === 1) {
        const urlParams = new URL(window.location.href);
        reloadAuthorized();
        window.location.href = urlParams.origin;
        // yield put(routerRedux.push({pathname: '/'}));
      }else{
        errMassage(response.msg);
      }
    },
    *logout(_, { call,put }) {
      const response = yield call(deleteUserInfo, {});
      yield put({
        type: 'changeLoginStatus',
        payload: {
          status: false,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/login',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
      if (response.success !== 1) {
        errMassage(response.msg);
      }
    },
    *getBackMobileVerCode({ payload }, { call, put }) {
      const response = yield call(getBackMobileVerCode, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      if(!payload.response){
        return {
          ...state,
          status: 0,
          massage:"失败",
          type: payload.type,
        };
      }
      return {
        ...state,
        status: payload.response.success,
        massage:payload.response.msg,
        type: payload.type,
      };
    },
  },
};
